﻿#include "mainwindow.h"

#include <QApplication>
#include <QMutex>
#include <thread>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    // 加锁
    static QMutex mutex;
    mutex.lock();

    QString text;

    switch(type)
    {
    case QtDebugMsg:
        text = QString("debug");
        break;

    case QtWarningMsg:
        text = QString("warning");
        break;

    case QtCriticalMsg:
        text = QString("critical");
        break;

    case QtFatalMsg:
        text = QString("fatal");
        break;

    case QtInfoMsg:
        text = QString("info");
        break;
    }

    // 设置输出信息格式


    QString current_date_time = QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss.zzz]");

    std::thread::id id = std::this_thread::get_id();
    std::stringstream sin;
    sin << id;
    std::string s = sin.str();
    QString current_process_thread = QString("(%1|%2)")
            .arg(QCoreApplication::applicationPid())
            .arg(QString(s.data()));

    QString context_file = QString("%1(%2)").arg(QString(context.file)).arg(context.line);
    QString context_function = context.function;
    QString message = QString("%1%2>%3#%4.%5 << %6")
            .arg(current_date_time)
            .arg(current_process_thread)
            .arg(context_file)
            .arg(context_function)
            .arg(text)
            .arg(msg);

    // 输出信息至文件中（读写、追加形式）
    QFile file(QDateTime::currentDateTime().toString("yyyy-MM-dd") + ".log");
    file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
    QTextStream text_stream(&file);
    text_stream << message <<endl;
    file.flush();
    file.close();

    QTextStream text_stream1(stderr);
    text_stream1 << message <<endl;

    // 解锁
    mutex.unlock();
}

int main(int argc, char *argv[])
{
    //qSetMessagePattern("%{time [yyyy-MM-dd hh:mm:ss.zzz]}%{appname}(%{pid}|%{threadid})>%{file}(%{line})#%{function}.%{type} << %{message}");
    qInstallMessageHandler(outputMessage);

    QApplication a(argc, argv);
    QFont f("黑体", 10);
    a.setFont(f);
    MainWindow w;
    w.show();
    return a.exec();
}
